package com.ruben.simplegraphql.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * SpringContextHolder
 *
 * @author VampireAchao
 * @since 2022/9/25
 */
@Lazy(false)
@Component("SpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static final String ERROR_MESSAGE = "applicationContext尚未注入";
    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> type) {
        return Optional.ofNullable(applicationContext).orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE)).getBean(type);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) Optional.ofNullable(applicationContext).orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE)).getBean(name);
    }

    @Override
    public void destroy() {
        setApplicationContext(null);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }


}